/**
 * 通用工具类jQuery插件
 * 作者： koal
 * 邮箱： koal@vip.qq.com
 * 时间： 2015年12月1日 0:01:27
 * 范例说明
 */
define([
    "msgTool",
    "bootstrapDialog",
    "css!global/plugins/bootstrap-dialog/bootstrap-dialog.css",
    "select2",
    "css!global/plugins/select2/select2.min.css",
    "css!global/plugins/select2/select2-bootstrap.css"
], function (msgTool, BootstrapDialog) {
    (function ($) {
        $.baseUtils = {

            /**
             * 基于 select2的下拉框重制版 封装
             * PS:如果数值是0，默认跳过
             */
            select: function (params) {
                //初始化皮肤
                //$.fn.select2.defaults.set("theme", "bootstrap");
                ////初始化语言
                //$.fn.select2.defaults.set("language", "zh-CN");
                var tokenSeparators = [',', '/', '、', ' '];
                var defaluts = {
                    dataName: params.dataName || "text",     //返回数据的JSON对应名字
                    dataVlue: params.dataVlue || "value",     //返回数据的JSON对应值
                    cssName: params.cssName || null,        //默认下拉框的DOM节点的css名称
                    url: params.url || null,                    //ajax远程链接
                    pageSize: 15,                            //默认显示数据条数
                    dataRows: "rows",                        //JSON数据列表节点名
                    dataTotal: "total",                      //JSON数据统计节点名
                    theme: "bootstrap",                     //初始化皮肤
                    language: "zh-CN",                      //初始化语言
                    allowClear: true,                       //删除按钮
                    placeholder: "请选择...",                //提示
                    multiple: false,                          //多选
                    width: "resolve",                        //宽度百分比
                    selectOnClose: false,                    //选择关闭
                    closeOnSelect: true,                     //选择后，是否自动关闭下拉框
                    tags: false,                              //自定义标签
                    cache: true,                              //启动缓存
                    maximumInputLength: 0,                   //最大允许字符数
                    maximumSelectionLength: 0,               //对于多选,可选数量
                    minimumResultsForSearch: Infinity,       //0最少显示的搜索结果,0显示，Infinity隐藏搜索框
                    minimumInputLength: 0,                    //最少输入长度
                    tokenSeparators: tokenSeparators,          //配置tags使用，触发哪个字符添加一个tags，此处为逗号和空格
                    containerCssClass: ':all:',              //css选择器:all:是所有
                    //formatInputTooShort: "请输入账号",
                    //formatNoMatches: "没有匹配的用户",
                    //formatSearching: "查询中...",
                    //格式化
                    escapeMarkup: function (markup) {
                        return markup;
                    },
                    //下拉内容选择与CSS美化
                    templateResult: templateResult,
                    //返回下拉内容和默认值
                    templateSelection: templateSelection,
                    //初始化赋值，新版已废弃
                    //initSelection: initSelection
                };

                var settings = $.extend({}, defaluts, params);

                function templateResult(repo) {
                    if (repo.loading) return repo.text;
                    var markup = repo[settings.dataName];
                    return markup;
                }

                function templateSelection(repo) {
                    repo.selected = true;
                    if (repo.text == null || repo.text == "" || repo.text == undefined) {
                        repo.text = settings.placeholder;
                    }
                    return repo[settings.dataName] || repo.text;
                };

                //判断ajax的url是否为空
                var getAjax = (settings.url == null) ? null : {
                    url: settings.url,
                    dataType: 'json',
                    delay: 250,
                    //不带搜索可以不要data属性
                    data: function (params) {
                        return {
                            search: params.term, //搜索关键词
                            offset: params.page
                        };
                    },
                    processResults: function (data, params) {
                        params.page = params.page || 1;
                        return {
                            results: data[settings.dataRows],
                            pagination: {
                                more: (params.page * settings.pageSize) < data[settings.dataTotal]
                            }
                        };
                    },
                    cache: settings.cache
                };

                var select = $(settings.cssName).select2({
                    placeholder: settings.placeholder,
                    theme: settings.theme,
                    multiple: settings.multiple,
                    language: settings.language,
                    allowClear: settings.allowClear,
                    width: settings.width,
                    selectOnClose: settings.selectOnClose,
                    closeOnSelect: settings.closeOnSelect,
                    tags: settings.tags,
                    cache: settings.cache,
                    maximumInputLength: settings.maximumInputLength,
                    maximumSelectionLength: settings.maximumSelectionLength,
                    minimumResultsForSearch: settings.minimumResultsForSearch,
                    minimumInputLength: settings.minimumInputLength,
                    tokenSeparators: settings.tokenSeparators,
                    containerCssClass: settings.containerCssClass,
                    escapeMarkup: settings.escapeMarkup,
                    templateResult: settings.templateResult,
                    templateSelection: settings.templateSelection,
                    //initSelection: settings.initSelection,新版已废弃
                    ajax: getAjax
                });
                return select;
            },
            /**
             * 初始化zTree（参数方法）
             */
            tree: function (obj) {
                var treeNodeName = obj.treeNodeName || null,			    //树节点名字*必填
                    isCheckNode = obj.isCheckNode || false,                 //检测选择的节点
                    checkType = obj.checkType || 0,                         //选择节点的类型ID
                    isCheck = obj.isCheck || false,							//单选多选方法控制,true多选，false（默认）单选
                    isCkStyle = obj.isCkStyle || false,						//选择样式,true是radio，false（默认）checkbox
                    ajaxUrl = obj.ajaxUrl || null,							//数据来源AJAX的URL*必填
                    autoParam = obj.autoParam || "ID",						//搜索传值
                    contentType = obj.contentType || "application/json",	//数据来源AJAX类型
                    methodType = obj.methodType || "POST",					//数据来源AJAX提交方式
                    idKey = obj.idKey || "id",								//数据来源下拉option的ID标示
                    pIdKey = obj.pIdKey || "pid",							//数据来源下拉option的父ID标示
                    rootPId = obj.rootPId || 0,								//数据来源下拉父option的ID识别
                    name = obj.name || "text",								//数据来源下拉option的text值标示
                    title = obj.title || "text",							//数据来源下拉option的title值标示
                    apiUrl = obj.apiUrl || null,								//充填数据，获取资源的URL
                    apiData = obj.apiData || null,								//充填数据，获取资源的参数
                    apiDataType = obj.apiDataType || "JSON",					//充填数据，获取资源的类型
                    apiMethod = obj.apiMethod || "POST",						//充填数据，AJAX提交方式
                    textValue = obj.textValue || "#values",					    //数据name展示的控件节点名称*必填
                    idValue = obj.idValue || "#ids",							//数据ID展示的控件节点名称*必填
                    isAction = obj.isAction || false,							//是否有其他动作
                    doAction = obj.doAction || null;							//执行其他动作
                var setting = {
                    view: {
                        dblClickExpand: true //双击打开
                    },
                    async: {
                        enable: true,
                        url: ajaxUrl,
                        autoParam: [autoParam],
                        contentType: contentType,
                        type: methodType,
                        dataFilter: filter
                    },
                    check: {
                        enable: isCheck,
                        chkStyle: isCkStyle ? "radio" : "checkbox"//radio,checkbox
                    },
                    data: {
                        simpleData: {
                            enable: true,
                            idKey: idKey,
                            pIdKey: pIdKey,
                            rootPId: rootPId
                        },
                        key: {
                            name: name,
                            title: title,
                            url: null
                        }
                    },
                    callback: {
                        onAsyncSuccess: asyncSuccess,//异步加载成功后执行
                        beforeClick: beforeClick,
                        onCheck: isCheck ? onCheck : null,	    //多选
                        onClick: isCheck ? null : onClick		//单击
                    }
                };


                //树过滤
                function filter(treeId, parentNode, childNodes) {
                    if (!childNodes) return null;
                    for (var i = 0, l = childNodes.length; i < l; i++) {
                        var cNodes = childNodes[i];
                        cNodes[name] = cNodes[name].replace(/\.n/g, '.');
                    }
                    return childNodes;
                }

                //加载完成
                function asyncSuccess(event, treeId, treeNode) {
                    //如果是多选才会提前复制
                    if (isCheck) {
                        $.ajax({
                            url: apiUrl,
                            method: apiMethod,
                            data: apiData,
                            dataType: apiDataType,
                            success: function (data, status) {
                                if (data.success) {
                                    var treeObj = $.fn.zTree.getZTreeObj(treeId);
                                    //得到字符串后切割成数组形式传递
                                    var ids = null;
                                    var names = null;
                                    if (data.model != null && (data.model.ids != undefined && data.model.names != undefined)) {
                                        ids = data.model.ids.split(",");
                                        names = data.model.names.split(",");
                                        $(idValue).val(ids);
                                        $(textValue).val(names);
                                        for (var i = 0, l = ids.length; i < l; i++) {
                                            var node = treeObj.getNodeByParam("id", ids[i]);
                                            treeObj.checkNode(node, true);
                                        }
                                    }

                                } else {
                                    msgTool.error("（多选）警告，数据加载失败，请刷新后重试！", "错误提示");
                                    return false;
                                }
                            }
                        })
                    }
                }

                //多选
                function onCheck(e, treeId, treeNode) {
                    var zTree = $.fn.zTree.getZTreeObj(treeId),
                        nodes = zTree.getCheckedNodes(true),
                        dataText = [], dataKey = [];
                    for (var i = 0, l = nodes.length; i < l; i++) {
                        dataText.push(nodes[i].text);
                        dataKey.push(nodes[i].id);
                    }
                    if (dataText.length > 0 && dataKey.length > 0) {
                        dataText = dataText.join(",");
                        dataKey = dataKey.join(",");
                    }

                    $(idValue).val(dataKey);
                    $(textValue).val(dataText);
                }

                //单选
                function onClick(e, treeId, treeNode) {
                    console.log("工具");
                    var zTree = $.fn.zTree.getZTreeObj(treeId),
                        nodes = zTree.getSelectedNodes(true);
                    nodes.sort(function compare(a, b) {
                        return a.id - b.id;
                    });
                    $(idValue).val(nodes[0].id);
                    $(textValue).val(nodes[0].text);
                    //关联到某页面的doAction方法
                    if (isAction) {
                        doAction(nodes[0]);
                    }
                }

                function beforeClick(treeId, treeNode) {
                    // var check = (treeNode && !treeNode.isParent);
                    // if (!check) alert("只能选择城市...");
                    // var check = treeNode;
                    // return check;
                    if (isCheckNode) {
                        if (checkType === treeNode.type) {
                            return true;
                        } else {
                            console.log("只能选择部门小组");
                            return false;
                        }
                    }
                    return treeNode;
                }

                $(document).ready(function () {
                    $.fn.zTree.init($(treeNodeName), setting).expandAll(true);
                });
            },

            /**
             * 通用AJAX
             */
            ajax: function (obj) {
                var url = obj.url || null,
                    data = obj.data || null,
                    method = obj.method || "POST",
                    contentType = obj.contentType || "application/x-www-form-urlencoded;charset=UTF-8",
                    text = obj.text || null,
                    isTable = obj.isTable || false, 	//是否bootstarp-table列表表格，0是，1否
                    tableName = obj.tableName || null, 	//bootstarp-table列表e名字，和isTable结合
                    isDialog = obj.isDialog || false, 	//是否dialog弹窗，0是，1否
                    skip = obj.skip || null;			//跳转路径
                $.ajax({
                    url: url,
                    method: method,
                    dataType: "json",
                    contentType: contentType,
                    data: data,
                    beforeSend: function () {
                        //触发ajax请求开始时执行
                        $("#doSubmit").text('提交中...');
                        $("#doSubmit").attr('disabled', 'disabled');
                    },
                    success: function (data, status) {
                        if (data.success) {
                            msgTool.success("恭喜您，数据" + text + "成功！", "信息提示");
                            if (isDialog) {
                                obj.dialog.close();
                            }
                            if (isTable && (tableName != null && tableName != undefined && tableName != '')) {
                                $(tableName).bootstrapTable('refresh');
                            }

                            if (skip != null) {
                                //延迟500毫秒后跳转
                                setTimeout(function () {
                                    location.href = skip;
                                }, 500);
                            }
                        } else {
                            msgTool.error(data.msg, "错误提示");
                            if (isDialog) {
                                obj.dialog.close();
                            }
                        }
                    },
                    complete: function () {
                        $("#doSubmit").text("提交审核");
                        $("#doSubmit").removeAttr('disabled');
                    },
                    error: function (jqXHR, textStatus) {
                        msgTool.error(jqXHR.status + " (" + jqXHR.statusText + ")", "错误提示");
                    }
                })
            },
            /**
             * 通用POST
             */
            post: function (obj) {
                var url = obj.url || null,
                    data = obj.data || null,
                    text = obj.text || null,
                    isDialog = obj.isDialog || false; //是否dialog提示框，0是，1否
                $.post(url, data,
                    function (data) {
                        if (data.success) {
                            msgTool.success("恭喜您，数据" + text + "成功！", "信息提示");
                            if (isDialog) {
                                obj.dialog.close();
                            }
                        } else {
                            msgTool.error(data.msg, "错误提示");
                            if (isDialog) {
                                obj.dialog.close();
                            }
                        }
                    }, "json");
            },
            /**
             * 启用/禁用弹窗JS封装
             * @param obj
             */
            oneStatus: function (obj) {
                var title = obj.title || '信息提示',
                    id = obj.row.id || null,				//必选
                    pid = obj.row.pid || null,				//必选
                    tableName = obj.tableName || null,		//必选
                    nameValue = obj.nameValue || null,		//必选
                    onText = obj.onText || '启动',			//选填，启动按钮文字
                    offText = obj.offText || '禁用',			//选填，禁用按钮文字
                    nameText = obj.nameText || null,		//必选
                    url = obj.url || null,					//必选
                    myStatus = obj.row.status || 0;
                BootstrapDialog.show({
                    title: title,
                    message: (myStatus === 1 || myStatus === "Y") ? '确认要' + offText + nameText + '『' + nameValue + '』吗?' : '确认要' + onText + nameText + '『' + nameValue + '』吗?',
                    type: BootstrapDialog.TYPE_DEFAULT,
                    closable: true,
                    draggable: true,
                    buttons: [{
                        label: '取消',
                        cssClass: 'btn-white',
                        icon: 'fa fa-times',
                        action: function (dialogItself) {
                            dialogItself.close();
                        }
                    }, {
                        label: '确定',
                        cssClass: 'btn-primary',
                        icon: 'fa fa-check',
                        action: function (dialogItself) {
                            if (id == null) {
                                if (obj.row.uuid != null) {
                                    id = obj.row.uuid;
                                }
                                if (obj.row.unid != null) {
                                    id = obj.row.unid;
                                }
                            }

                            $.ajax({
                                url: url,
                                method: "POST",
                                dataType: "json",
                                data: {
                                    id: id,
                                    pid: pid,
                                    statusStr: obj.row.status === "Y" ? "N": "Y",
                                    status: myStatus === 1 ? 0 : 1
                                },
                                success: function (data) {
                                    if (data.success) {
                                        msgTool.success("恭喜您，" + nameText + (myStatus === 1 ? offText : onText) + "成功！", "信息提示");
                                        tableName.bootstrapTable('refresh');
                                        dialogItself.close();
                                        return false;
                                    } else {
                                        msgTool.error("警告，" + data.msg, "错误提示");
                                        dialogItself.close();
                                        return false;
                                    }
                                },
                                error: function (jqXHR) {
                                    msgTool.error(jqXHR.status + " (" + jqXHR.statusText + ")", "错误提示");
                                    dialogItself.close();
                                    return false;
                                }
                            });
                        }
                    }]
                });
            },


            /**
             * 认领弹窗更改状态
             */
            claimStatus: function (obj) {
                var title = obj.title || '信息提示',
                    id = obj.row.id || null,				//必选
                    itemId = obj.row.itemId || null,	    //必选
                    itemName = obj.row.itemName || null,	    //必选
                    tableName = obj.tableName || null,		//必选
                    nameValue = obj.nameValue || null,		//必选
                    applyStatus = obj.applyStatus || 0,		//必选
                    onText = obj.onText || '认领',			//选填
                    nameText = obj.nameText || null,		//必选
                    url = obj.url || null,					//必选
                    leftButton = obj.leftButton || '取消',
                    rightButton = obj.rightButton || '确定';
                BootstrapDialog.show({
                    title: title,
                    message: '确认要' + onText + '『' + nameValue + '』的' + nameText +'吗?',
                    type: BootstrapDialog.TYPE_DEFAULT,
                    closable: true,
                    draggable: true,
                    buttons: [{
                        label: leftButton,
                        cssClass: 'btn-white',
                        icon: 'fa fa-times',
                        action: function (dialogItself) {
                            dialogItself.close();
                        }
                    }, {
                        label: rightButton,
                        cssClass: 'btn-primary',
                        icon: 'fa fa-check',
                        action: function (dialogItself) {
                            $.ajax({
                                url: url,
                                method: "POST",
                                dataType: "json",
                                data: {
                                    id: id,
                                    itemId: itemId,
                                    itemName: itemName,
                                    applyStatus: applyStatus
                                },
                                success: function (data) {
                                    if (data.success) {
                                        msgTool.success("恭喜您，" + nameText + (onText) + "成功！", "信息提示");
                                        tableName.bootstrapTable('refresh');
                                        dialogItself.close();
                                        return false;
                                    } else {
                                        msgTool.error("警告，" + data.msg, "错误提示");
                                        dialogItself.close();
                                        return false;
                                    }
                                },
                                error: function (jqXHR) {
                                    msgTool.error(jqXHR.status + " (" + jqXHR.statusText + ")", "错误提示");
                                    dialogItself.close();
                                    return false;
                                }
                            })
                        }
                    }]
                });
            },
            

            /**
             * 受理弹窗更改状态
             */
            handleState: function (obj) {
                var title = obj.title || '信息提示',
                    projId = obj.row.projId || null,				//必选
                    serviceName = obj.row.serviceName || null,	    //必选
                    tableName = obj.tableName || null,		//必选
                    nameValue = obj.nameValue || null,		//必选
                    handleState = obj.handleState || 0,		//必选
                    onText = obj.onText || '受理',			//选填
                    nameText = obj.nameText || null,		//必选
                    url = obj.url || null,					//必选
                    leftButton = obj.leftButton || '取消',
                    rightButton = obj.rightButton || '确定';
                BootstrapDialog.show({
                    title: title,
                    message: '确认要' + onText + nameText + '『' + nameValue + '』&nbsp;吗?',
                    type: BootstrapDialog.TYPE_DEFAULT,
                    closable: true,
                    draggable: true,
                    buttons: [{
                        label: leftButton,
                        cssClass: 'btn-white',
                        icon: 'fa fa-times',
                        action: function (dialogItself) {
                            dialogItself.close();
                        }
                    }, {
                        label: rightButton,
                        cssClass: 'btn-primary',
                        icon: 'fa fa-check',
                        action: function (dialogItself) {
                            $.ajax({
                                url: url,
                                method: "POST",
                                dataType: "json",
                                data: {
                                	projId: projId,
                                	handleState: handleState
                                },
                                success: function (data) {
                                    if (data.success) {
                                        msgTool.success("恭喜您，" + nameText + (onText) + "成功！", "信息提示");
                                        tableName.bootstrapTable('refresh');
                                        dialogItself.close();
                                        return false;
                                    } else {
                                        msgTool.error("警告，" + data.msg, "错误提示");
                                        dialogItself.close();
                                        return false;
                                    }
                                },
                                error: function (jqXHR) {
                                    msgTool.error(jqXHR.status + " (" + jqXHR.statusText + ")", "错误提示");
                                    dialogItself.close();
                                    return false;
                                }
                            })
                        }
                    }]
                });
            },
            /**
             * 单个删除
             * @param obj
             */
            oneDelete: function (obj) {
                var title = obj.title || '信息提示',
                    uuid = obj.row.uuid || null,			//选
                    id = obj.row.id || null,				//必选
                    tableName = obj.tableName || null,		//必选
                    nameValue = obj.nameValue || null,		//必选
                    nameText = obj.nameText || null,		//必选
                    url = obj.url || null;					//必选
                BootstrapDialog.show({
                    title: title,
                    message: '确认要删除' + '『' + nameValue + '』的' + nameText + '吗?',
                    type: BootstrapDialog.TYPE_DEFAULT,
                    closable: true,
                    draggable: true,
                    buttons: [{
                        label: '取消',
                        cssClass: 'btn-white',
                        icon: 'fa fa-times',
                        action: function (dialogItself) {
                            dialogItself.close();
                        }
                    }, {
                        label: '确定',
                        cssClass: 'btn-primary',
                        icon: 'fa fa-check',
                        action: function (dialogItself) {
                            $.ajax({
                                url: url,
                                method: "POST",
                                dataType: "json",
                                data: {
                                    id: uuid != null ? uuid : id
                                },
                                success: function (data) {
                                    if (data.success) {
                                        msgTool.success("恭喜您，" + nameText + "删除成功！", "信息提示");
                                        tableName.bootstrapTable('refresh');
                                        dialogItself.close();
                                        return false;
                                    } else {
                                        msgTool.error("警告，" + data.msg, "错误提示");
                                        dialogItself.close();
                                        return false;
                                    }
                                },
                                error: function (jqXHR) {
                                    msgTool.error(jqXHR.status + " (" + jqXHR.statusText + ")", "错误提示");
                                    dialogItself.close();
                                    return false;
                                }
                            })
                        }
                    }]
                });
            },
            //批量更改（带HTML选项）
            batchAction: function (obj) {
                var title = obj.title || '信息提示',
                    isEntity = obj.isEntity || false,       //是否传输实体
                    tableName = obj.tableName || null,		//必选
                    nameValue = obj.nameValue || null,		//必选
                    nameText = obj.nameText || null,		//必选
                    onText = obj.onText || '启动',			//选填，启动按钮文字
                    offText = obj.offText || '禁用',			//选填，禁用按钮文字
                    infoText = obj.infoText || '状态',		//选填
                    onshown = obj.onshown || null,          //窗口弹出完成后，执行的函数
                    htmlKit = obj.htmlKit || null,          //弹窗内部的html组件（input、select等）
                    htmlNode = obj.htmlNode || null,       //弹窗内部的html组件的节点选择器
                    beanField = obj.beanField || 'status', //对应后台bean的字段
                    idsList = obj.row,
                    batchType = obj.batchType || 1, 		//1：状态，2：密码，3：删除
                    url = obj.url || null;					//必选

                function run(dialogItself, value, fields) {
                    var postData;
                    if (isEntity) {
                        postData = JSON.stringify(idsList);
                    } else {
                        postData = JSON.parse('{"idsList": ["' + idsList + '"], "' + fields + '": "' + value + '"}');
                    }
                    $.ajax({
                        url: url,
                        method: "POST",
                        dataType: "json",
                        contentType: isEntity ? 'application/json' : 'application/x-www-form-urlencoded',
                        data: postData,
                        success: function (data) {
                            if (data.success) {
                                if (batchType == 1) {
                                    msgTool.success("恭喜您，" + nameText + "全部" + (value == 1 ? onText : offText) + "成功！", "信息提示");
                                }
                                if (batchType == 2) {
                                    msgTool.success("恭喜您，已选" + nameText + "的密码初始化成功！<br>密码为：123456", "信息提示");
                                }
                                if (batchType == 3) {
                                    msgTool.success("恭喜您，已选" + nameText + "删除成功！", "信息提示");
                                }
                                if (batchType == 4) {
                                    msgTool.success("恭喜您，已选" + nameText + "的" + infoText + "更改成功！", "信息提示");
                                }
                                tableName.bootstrapTable('refresh');
                                dialogItself.close();
                                return false;
                            } else {
                                msgTool.error("警告，" + data.msg, "错误提示");
                                dialogItself.close();
                                return false;
                            }
                        },
                        error: function (jqXHR) {
                            msgTool.error(jqXHR.status + " (" + jqXHR.statusText + ")", "错误提示");
                            dialogItself.close();
                            return false;
                        }
                    })
                };
                //自定义按钮
                var myButtons = [];
                //1【取消，禁用，启用】，2，3：【取消，执行】
                if (batchType == 1) {
                    myButtons = [{
                        label: '取消',
                        cssClass: 'btn-white',
                        icon: 'fa fa-times',
                        action: function (dialogItself) {
                            dialogItself.close();
                        }
                    }, {
                        label: '全部' + offText,
                        cssClass: 'btn-warning',
                        icon: 'fa fa-ban',
                        action: function (dialogItself) {
                            run(dialogItself, 0, beanField);
                        }
                    }, {
                        label: '全部' + onText,
                        cssClass: 'btn-primary',
                        icon: 'fa fa-check',
                        action: function (dialogItself) {
                            run(dialogItself, 1, beanField);
                        }
                    }];
                } else if (batchType == 2 || batchType == 3 || batchType == 4) {
                    myButtons = [{
                        label: '取消',
                        cssClass: 'btn-white',
                        icon: 'fa fa-times',
                        action: function (dialogItself) {
                            dialogItself.close();
                        }
                    }, {
                        label: '提交操作',
                        cssClass: 'btn-primary',
                        icon: 'fa fa-check',
                        action: function (dialogItself) {
                            if (htmlKit != null) {
                                run(dialogItself, $(htmlNode).val() == null ? 0 : $(htmlNode).val(), beanField);
                            } else {
                                run(dialogItself, 1, beanField);
                            }

                        }
                    }];
                }

                function message() {
                    if (batchType == 1) {
                        // return '确认要批量更改' + nameText + '<br />『' + nameValue + '』<br />的' + infoText + '吗?';
                        return '确认要批量更改' + nameText + '的' + infoText + '吗？';
                    }
                    if (batchType == 2) {
                        // return '确认要批量更改' + nameText + '<br />『' + nameValue + '』<br />的密码吗?';
                        return '确认要批量更改' + nameText + '的密码吗？修改后密码为：123456';
                    }
                    if (batchType == 3) {
                        // return '确认要批量删除' + nameText + '<br />『' + nameValue + '』<br />吗?';
                        return '确认要批量删除' + nameText + '吗？';
                    }
                    if (batchType == 4) {
                        // return '确认要批量更改已选' + nameText + '的' + infoText + '吗?<br><br>' + htmlKit;
                        return '确认要批量更改已选' + nameText + '的' + infoText + '吗？<br><br>' + htmlKit;
                    }
                }

                BootstrapDialog.show({
                    title: title,
                    message: message,
                    type: BootstrapDialog.TYPE_DEFAULT,
                    closable: true,
                    draggable: true,
                    buttons: myButtons,
                    onshown: onshown
                });
            },
            /**
             * 刷新table列表
             */
            refreshTable: function (obj) {
                var talbName = obj.talbName || null,		//必选
                    url = obj.url || null,						//必选
                    key = obj.key || null,
                    val = obj.val || null;
                var attr = url ? url + '?' + key + '=' + val : null;
                $(talbName).bootstrapTable('refresh', {url: attr})
            },
            modal: function (params) {
                var defaluts = {
                    title: "消息",
                    closable: true,				//关闭箭头启动
                    closeByBackdrop: false,		//点击空白不消失
                    closeByKeyboard: true,		//ESC取消禁用
                    sync: false,					//是否远程html
                    htmlUrl: null,				//远程html
                    message: "消息",				//模态框提示消息
                    ajaxUrl: null,				//ajax提交的url地址
                    data: null					//ajax提交的DATA数据

                };
                var settings = $.extend({}, defaluts, params);
                BootstrapDialog.show({
                    type: BootstrapDialog.TYPE_DEFAULT,
                    title: settings.title,
                    closable: settings.closable,	//关闭箭头启动
                    closeByBackdrop: settings.closeByBackdrop,	//点击空白不消失
                    closeByKeyboard: settings.closeByKeyboard,//ESC取消禁用
                    message: settings.sync == true ? $('<div></div>').load(settings.htmlUrl) : settings.message,
                    data: {
                        'row': settings.row,
                    },
                    buttons: [{
                        label: '取消',
                        cssClass: 'btn-white cancel',
                        icon: 'fa fa-times',
                        action: function (dialog) {
                            dialog.close();
                        }
                    }, {
                        label: '提交' + settings.title,
                        //hotkey: 13,//回车提交
                        cssClass: 'btn-primary',
                        icon: 'fa fa-check',
                        action: function (dialog) {
                            $.baseUtils.post({
                                url: settings.ajaxUrl,
                                data: settings.data,
                                text: settings.title,
                                isDialog: true,
                                dialog: dialog
                            })
                        }
                    }]
                });
            },

            Dialog: function (params) {
                var title = params.title || null;
                var func = params.func || null;
                BootstrapDialog.show({
                    title: '信息提示',
                    message: '确认要' + title + '吗?',
                    type: BootstrapDialog.TYPE_DEFAULT,
                    closable: true,
                    draggable: true,
                    buttons: [{
                        label: '取消',
                        cssClass: 'btn-white',
                        icon: 'fa fa-times',
                        action: function (dialogItself) {
                            dialogItself.close();
                        }
                    }, {
                        label: '确定',
                        cssClass: 'btn-primary',
                        icon: 'fa fa-check',
                        action: function (dialogItself) {
                            func();
                            msgTool.success("恭喜您，操作" + title + "成功！", "信息提示");
                            dialogItself.close();
                        }
                    }]
                });
            },

            /**
             * 弹窗ajax
             *
             *
             * @param params
             */
            dialogAjax: function (params) {
                var data = params.data || null;               //数据
                var title = params.title || "信息提示";        //弹窗title
                var preMsg = params.preMsg || "确定执行吗！"; //弹窗前置提示
                var sucMsg = params.sucMsg || "执行成功！";  //成功提示
                var errMsg = params.errMsg || null;         //失败提示
                var url = params.url || null;               //ajax
                var reload = params.reload || false;        //是否刷新
                var contentType = params.contentType || 'application/x-www-form-urlencoded';//提交数据类型（application/json）
                BootstrapDialog.show({
                    title: title,
                    message: preMsg,
                    type: BootstrapDialog.TYPE_DEFAULT,
                    closable: true,
                    draggable: true,
                    buttons: [{
                        label: '取消',
                        cssClass: 'btn-white',
                        icon: 'fa fa-times',
                        action: function (dialogItself) {
                            dialogItself.close();
                        }
                    }, {
                        label: '确定',
                        cssClass: 'btn-primary',
                        icon: 'fa fa-check',
                        action: function (dialogItself) {
                            $.ajax({
                                url: url,
                                method: "POST",
                                dataType: "json",
                                contentType: contentType,
                                data: data,
                                success: function (data) {
                                    if (data.success) {
                                        msgTool.success(sucMsg, "成功提示");
                                        dialogItself.close();
                                        if (reload) {
                                            window.location.reload();
                                        }
                                        return false;
                                    } else {
                                        msgTool.error(errMsg ? errMsg : ("警告！" + data.msg), "错误提示");
                                        dialogItself.close();
                                        return false;
                                    }
                                },
                                error: function (jqXHR) {
                                    msgTool.error(jqXHR.status + " (" + jqXHR.statusText + ")", "错误提示");
                                    dialogItself.close();
                                    return false;
                                }
                            })
                        }
                    }]
                });
            },

            /**
             * 推送：1新增，2更新
             * @param params
             */
            pushUrl: function (params) {
                var videoIds = params.data || null;
                var title = params.title || "推送提示";
                var body = params.body || null;
                var url = params.url || null;
                var pushButton = function (dialogItself, pushType) {
                    $.ajax({
                        url: url,
                        method: "POST",
                        dataType: "json",
                        data: {
                            videoIds: videoIds,
                            pushType: pushType
                        },
                        success: function (data) {
                            if (data.success) {
                                msgTool.success("恭喜您，《" + body + "》推送" + (pushType == 1 ? "新增" : "更新") + "成功！", "信息提示");
                                dialogItself.close();
                                return false;
                            } else {
                                msgTool.error("警告！" + data.msg, "错误提示");
                                dialogItself.close();
                                return false;
                            }
                        },
                        error: function (jqXHR) {
                            msgTool.error(jqXHR.status + " (" + jqXHR.statusText + ")", "错误提示");
                            dialogItself.close();
                            return false;
                        }
                    })
                };
                BootstrapDialog.show({
                    title: title,
                    message: "确定要推送《" + body + "》的链接到百度吗？",
                    type: BootstrapDialog.TYPE_DEFAULT,
                    closable: true,
                    draggable: true,
                    buttons: [{
                        label: '取消',
                        cssClass: 'btn-white',
                        icon: 'fa fa-times',
                        action: function (dialogItself) {
                            dialogItself.close();
                        }
                    }, {
                        label: '新增推送',
                        cssClass: 'btn-primary',
                        icon: 'fa fa-plus-square',
                        action: function (dialogItself) {
                            pushButton(dialogItself, 1);
                        }
                    }, {
                        label: '更新推送',
                        cssClass: 'btn-success',
                        icon: 'fa fa-cloud-upload',
                        action: function (dialogItself) {
                            pushButton(dialogItself, 2);
                        }
                    }]
                });
            },
            /**
             * 上传
             * @param obj
             */
            uploader: function (obj) {
                var uploadUrl = obj.uploadUrl || '/common/uploader/index',
                    layoutTemplates = obj.layoutTemplates,
                    filesType = obj.filesType || 0,                     //文件类型,0图片,1文件
                    uploadLabel = obj.uploadLabel,
                    browseLabel = obj.browseLabel,
                    appendCode = obj.appendCode || "",                  //附加按钮
                    showCaption = obj.showCaption || false,                //是否显示上传输入框
                    rootName = obj.rootName,                            //父节点
                    cssName = obj.cssName || "body",		             //必选
                    maxFileSize = obj.fileSize || 102400,               //最大文件大小(单位KB,100M)
                    errorCss = obj.errorCssName || "#error-message",    //错误css名字
                    browseClass = obj.browseClass || 'btn btn-danger btn-outline',   //浏览样式
                    uploadClass = obj.uploadClass || 'btn btn-danger btn-outline',   //上传样式
                    fileExtensions = obj.fileExtensions || null;        //文件扩展
                if (fileExtensions == null) {
                    if (filesType == 0) {
                        fileExtensions = ['jpg', 'gif', 'png', 'jpeg'];
                    } else {
                        fileExtensions = ['jpg', 'png', 'gif', 'jpeg', 'txt', 'zip', 'rar', '7z', 'doc', 'docx', 'xlsx', 'xls', 'pdf', 'ppt'];
                    }
                }

                /**
                 * 获取布局模板
                 */
                function getLayoutTemplates() {
                    if (layoutTemplates == null || layoutTemplates == undefined) {
                        return {
                            main2: (appendCode == null ? "" : appendCode) + ' {upload} {browse}',
                            progress: ' {progress} '
                        }
                    }
                    return layoutTemplates;
                }
                //声明节点
                var fileNode;
                //判断节点
                if (rootName != null && typeof(rootName) != 'undefined') {
                    fileNode = $(rootName).find(cssName);
                } else {
                    fileNode = $(cssName);
                }
                return fileNode.fileinput({
                    language: 'zh',                                 //设置语言
                    uploadUrl: uploadUrl,                           //上传的地址
                    method: 'post',
                    uploadLabel: uploadLabel,
                    browseLabel: browseLabel,
                    uploadExtraData: {filesType: filesType},        //附加属性
                    allowedFileExtensions: fileExtensions,
                    showPreview: false,                             //是否显示图片展示框
                    showUpload: true,                               //是否显示上传按钮
                    showCaption: showCaption,                             //是否显示上传输入框
                    showRemove: false,                              //是否显示删除键
                    browseIcon: '<i class="fa fa-folder-open-o" aria-hidden="true"></i>&nbsp;', //浏览图标
                    browseClass: browseClass,                                                    //浏览样式
                    uploadIcon: '<i class="fa fa-upload" aria-hidden="true"></i>',              //上传图标
                    uploadClass: uploadClass,                                                    //上传样式
                    maxFileSize: maxFileSize,                                                   //单位为kb，如果为0表示不限制文件大小
                    elErrorContainer: errorCss,                                                 //错误显示位置
                    msgErrorClass: 'alert alert-block alert-danger',                            //错误显示位置节点样式
                    validateInitialCount: true,

                    layoutTemplates: getLayoutTemplates

                });
            },
            other: {},
        }

    })(jQuery);

});
